

angular.module('chat.services', [])

.factory('SocketFactory', function ($rootScope) {
    if (_app_name == "nonghua") {
      var socket =  io.connect('wss://www.junong360.com:9999',{transports: ['websocket']});
    } else if (_app_name == "expert") {
      var socket =  io.connect('ws://www.metercomm.com.cn:9998',{transports: ['websocket']});
    } else {
      var socket =  io.connect('ws://127.0.0.1:9999',{transports: ['websocket']});
    } 
    if (socket.connected === false) {
      $rootScope.status = 'offline';
    }
    var disconnect = false;
    return {
      //connect: function (ip, port) {
      //  socket =  io.connect('ws://' + ip + ':' + port,{transports: ['websocket']});io.connect()
      //},
      on: function (eventName, callback) {
        socket.on(eventName, function() {
          var args = arguments;
          if (!disconnect) {
            $rootScope.$apply(function() {
              callback.apply(socket, args);
            });
          }
        });
      },
      emit: function (eventName, data, callback) {
        socket.emit(eventName, data, function() {
          var args = arguments;
          $rootScope.$apply(function() {
            if (callback) {
              callback.apply(socket, args);
            }
          });
        });
      },
      upload: function (eventName, file, data, callback, fnPercentage, fnComplete) {
        var stream = ss.createStream();
        ss(socket).emit(eventName, stream, data, function() {
          var args = arguments;
          $rootScope.$apply(function() {
            if (callback) {
              callback.apply(socket, args);
            }
          });
        });

        var blobStream = ss.createBlobReadStream(file);
        var size = 0;
        var prevTime = (new Date()).getTime();

        blobStream.on('data', function(chunk) {
          size += chunk.length;
          var percent = Math.floor(size / file.size * 100);

          var curTime = (new Date()).getTime();
          if (curTime - prevTime >= 500) {
            fnPercentage(percent);
            prevTime = curTime;
          }
        }).on('end', function() {
          stream.end();
          fnComplete();
        });
        blobStream.pipe(stream);
      },
      disconnect: function() {
        disconnect = true;
        socket.disconnect();
      }
    }
  })
